<?php

namespace app\admin\controller;

use app\common\controller\Backend;

/**
 * 产品原料配方
 *
 * @icon fa fa-circle-o
 */
class ClothmakingRecipe extends Backend
{

    /**
     * ClothmakingRecipe模型对象
     * @var \app\admin\model\ClothmakingRecipe
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\ClothmakingRecipe;

    }

    /**
     * 新增
     */
    public function add()
    {
        if (
            $this->request->isPost()
        ) {
            $params = $this->request->post("row/a");
            if ($params) {
                foreach ($params as $key => $value) {
                    if (strpos($key, 'ingredients') === 0) {
                        unset($params[$key]);
                    }
                }
                // 直接保存模型
                $result = $this->model->save($params);
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error($this->model->getError());
                }
            } else {
                $this->error('参数错误');
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                // 移除前端提交的多余字段
                foreach ($params as $key => $value) {
                    if (strpos($key, 'ingredients') === 0) {
                        unset($params[$key]);
                    }
                }
                // 处理ingredient_details字段
                if (isset($params['ingredient_details'])) {
                    if (is_array($params['ingredient_details'])) {
                        // 如果已经是数组，直接转换为JSON字符串
                        $params['ingredient_details'] = json_encode($params['ingredient_details'], JSON_UNESCAPED_UNICODE);
                    } elseif (is_string($params['ingredient_details'])) {
                        // 如果是字符串，尝试解码后重新编码确保格式一致
                        $decoded = json_decode($params['ingredient_details'], true);
                        if (json_last_error() === JSON_ERROR_NONE) {
                            $params['ingredient_details'] = json_encode($decoded, JSON_UNESCAPED_UNICODE);
                        }
                    }
                }

                // 查找现有记录并更新
                $row = $this->model->find($ids);
                if (!$row) {
                    $this->error('记录未找到');
                }

                $result = $row->save($params);
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error($row->getError());
                }
            } else {
                $this->error('参数错误');
            }
        }

        // 获取数据并传递给视图
        $row = $this->model->find($ids);
        if ($row) {
            // 确保ingredient_details字段正确处理
            if (isset($row['ingredient_details']) && is_string($row['ingredient_details'])) {
                $decoded = json_decode($row['ingredient_details'], true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    $row['ingredient_details'] = $decoded;
                }
            }
            $this->view->assign('row', $row);
        }

        return $this->view->fetch();
    }

    public function getRecipeById(){
        $id = $this->request->param('id');
        $recipe = $this->model->where('id', $id)->find();
        if ($recipe) {
            $recipe['ingredient_details'] = json_decode($recipe['ingredient_details'], true);
            $this->success('', null, $recipe);
        } else {
            $this->error('未找到该配方');
        }
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
